package com.eidos.blogs.openapi.utils;


import com.eidos.blogs.openapi.constant.NcountKey;
import com.eidos.blogs.openapi.exception.NCountDemoException;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

public class KeyUtils {

    /**
     * 加载私钥
     */
    public static PrivateKey loadPrivateKey(String privateKey) throws NCountDemoException {
        // 去除头尾标志
        // 去除换行符
        privateKey = privateKey.replace("\r", "").replace("\n", "").replace(" ", "");
        byte[] bPriKey = Base64Util.decode(privateKey);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bPriKey);
        KeyFactory keyFactory;
        try {
            keyFactory = KeyFactory.getInstance(NcountKey.ALGORITHM);
            PrivateKey key = keyFactory.generatePrivate(keySpec);
            return key;
        } catch (Exception e) {
            e.printStackTrace();
            throw new NCountDemoException("加载私钥异常", e);
        }
    }
}
